<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课程管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu-section {
            padding: 10px 20px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            border-bottom: 1px solid #3c5166;
            margin-top: 15px;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .search-box {
            display: flex;
            width: 300px;
        }

        .search-box input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            outline: none;
        }

        .search-box button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }

        .add-button {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #333;
        }

        tr:hover {
            background-color: #f5f7f9;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .edit-button,
        .delete-button {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .edit-button {
            background-color: #3498db;
            color: white;
        }

        .delete-button {
            background-color: #e74c3c;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow-y: auto;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 20px;
            box-sizing: border-box;
        }

        .modal-content {
            background-color: white;
            margin: 20px auto;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        .form-group textarea {
            height: 100px;
            resize: vertical;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn-cancel,
        .btn-save {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-cancel {
            background-color: #f1f1f1;
            color: #333;
        }

        .btn-save {
            background-color: #2ecc71;
            color: white;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">admin1</span> - 管理员
                </div>
            </div>
            <div class="menu-section">基础管理</div>
            <ul class="menu">
                <li><a href="/admin/dashboard">系统概览</a></li>
                <li><a href="/admin/teachers">教师管理</a></li>
                <li><a href="/admin/students">学生管理</a></li>
                <li class="active"><a href="/admin/courses">课程管理</a></li>
                <li><a href="/admin/classrooms">教室管理</a></li>
            </ul>

            <div class="menu-section">教务管理</div>
            <ul class="menu">
                <li><a href="/admin/course-selections">选课管理</a></li>
                <li><a href="/admin/grades">成绩管理</a></li>
            </ul>

            <div class="menu-section">系统设置</div>
            <ul class="menu">
                <li><a href="/admin/profile">个人信息</a></li>
            </ul>

            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>课程管理</h1>
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索课程...">
                    <button type="button" onclick="searchCourses()">搜索</button>
                </div>
                <button class="add-button" onclick="openAddModal()">添加课程</button>
            </div>

            <table id="coursesTable">
                <thead>
                    <tr>
                        <th>课程ID</th>
                        <th>课程名称</th>
                        <th>学分</th>
                        <th>总学时</th>
                        <th>开课学期</th>
                        <th>授课教师</th>
                        <th>教室</th>
                        <th>专业</th>
                        <th>课程类型</th>
                        <th>开课年份</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="coursesList">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加课程模态框 -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddModal()">&times;</span>
            <h2>添加课程</h2>
            <form id="addCourseForm">
                <div class="form-group">
                    <label for="addCourseId">课程ID</label>
                    <input type="text" id="addCourseId" name="courseId">
                </div>
                <div class="form-group">
                    <label for="addName">课程名称</label>
                    <input type="text" id="addName" name="name">
                </div>
                <div class="form-group">
                    <label for="addCredits">学分</label>
                    <input type="number" id="addCredits" name="credits" min="0" step="1">
                </div>
                <div class="form-group">
                    <label for="addTotalHours">总学时</label>
                    <input type="number" id="addTotalHours" name="totalHours" min="0" step="1">
                </div>
                <div class="form-group">
                    <label for="addSemester">开课学期</label>
                    <select id="addSemester" name="semester">
                        <option value="大一上">大一上</option>
                        <option value="大一下">大一下</option>
                        <option value="大二上">大二上</option>
                        <option value="大二下">大二下</option>
                        <option value="大三上">大三上</option>
                        <option value="大三下">大三下</option>
                        <option value="大四上">大四上</option>
                        <option value="大四下">大四下</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="addTeacherId">授课教师</label>
                    <select id="addTeacherId" name="teacherId">
                        <!-- 教师选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="addClassroomId">教室</label>
                    <select id="addClassroomId" name="classroomId">
                        <!-- 教室选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="addMajor">专业</label>
                    <input type="text" id="addMajor" name="major">
                </div>
                <div class="form-group">
                    <label for="addCourseType">课程类型</label>
                    <select id="addCourseType" name="courseType">
                        <option value="公选课">公选课</option>
                        <option value="必修课">必修课</option>
                        <option value="选修课">选修课</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="addYear">开课年份</label>
                    <input type="number" id="addYear" name="year" min="2000" max="2100">
                </div>
                <div class="form-group">
                    <label for="addDescription">课程描述</label>
                    <textarea id="addDescription" name="description"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" onclick="closeAddModal()">取消</button>
                    <button type="button" class="btn-save" onclick="addCourse()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑课程模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2>编辑课程</h2>
            <form id="editCourseForm">
                <div class="form-group">
                    <label for="editCourseId">课程ID</label>
                    <input type="text" id="editCourseId" name="courseId" readonly>
                </div>
                <div class="form-group">
                    <label for="editName">课程名称</label>
                    <input type="text" id="editName" name="name">
                </div>
                <div class="form-group">
                    <label for="editCredits">学分</label>
                    <input type="number" id="editCredits" name="credits" min="0" step="1">
                </div>
                <div class="form-group">
                    <label for="editTotalHours">总学时</label>
                    <input type="number" id="editTotalHours" name="totalHours" min="0" step="1">
                </div>
                <div class="form-group">
                    <label for="editSemester">开课学期</label>
                    <select id="editSemester" name="semester">
                        <option value="大一上">大一上</option>
                        <option value="大一下">大一下</option>
                        <option value="大二上">大二上</option>
                        <option value="大二下">大二下</option>
                        <option value="大三上">大三上</option>
                        <option value="大三下">大三下</option>
                        <option value="大四上">大四上</option>
                        <option value="大四下">大四下</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editTeacherId">授课教师</label>
                    <select id="editTeacherId" name="teacherId">
                        <!-- 教师选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="editClassroomId">教室</label>
                    <select id="editClassroomId" name="classroomId">
                        <!-- 教室选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="editMajor">专业</label>
                    <input type="text" id="editMajor" name="major">
                </div>
                <div class="form-group">
                    <label for="editCourseType">课程类型</label>
                    <select id="editCourseType" name="courseType">
                        <option value="公选课">公选课</option>
                        <option value="必修课">必修课</option>
                        <option value="选修课">选修课</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="editYear">开课年份</label>
                    <input type="number" id="editYear" name="year" min="2000" max="2100">
                </div>
                <div class="form-group">
                    <label for="editDescription">课程描述</label>
                    <textarea id="editDescription" name="description"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                    <button type="button" class="btn-save" onclick="updateCourse()">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 页面加载时获取所有课程
        document.addEventListener('DOMContentLoaded', function () {
            fetchCourses();
            fetchTeachers();
            fetchClassrooms();
        });

        // 获取所有课程
        function fetchCourses() {
            console.log("开始获取课程列表...");
            fetch('/api/admin/courses', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取课程列表响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取课程失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("成功获取课程列表数据:", data);
                    renderCourseList(data);
                })
                .catch(error => {
                    console.error('获取课程出错:', error);
                });
        }

        // 获取所有教师
        function fetchTeachers() {
            console.log("开始获取教师列表...");
            return fetch('/api/admin/teachers', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取教师列表响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取教师失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("成功获取教师列表数据:", data);
                    populateTeacherOptions(data);
                    return data; // 返回数据以便链式调用
                })
                .catch(error => {
                    console.error('获取教师出错:', error);
                    throw error; // 重新抛出错误以便调用者处理
                });
        }

        // 获取所有教室
        function fetchClassrooms() {
            console.log("开始获取教室列表...");
            return fetch('/api/admin/classrooms', {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取教室列表响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('获取教室失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("成功获取教室列表数据:", data);
                    populateClassroomOptions(data);
                    return data; // 返回数据以便链式调用
                })
                .catch(error => {
                    console.error('获取教室出错:', error);
                    throw error; // 重新抛出错误以便调用者处理
                });
        }

        // 渲染课程列表
        function renderCourseList(courses) {
            console.log("开始渲染课程列表...");
            const tableBody = document.getElementById('coursesList');
            tableBody.innerHTML = '';

            if (courses.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = '<td colspan="11" style="text-align: center;">没有找到课程</td>';
                tableBody.appendChild(emptyRow);
                console.log("课程列表为空");
                return;
            }

            courses.forEach(course => {
                // 安全转义课程ID，防止特殊字符导致问题
                const safeId = course.courseId.replace(/'/g, "\\'").replace(/"/g, '\\"');
                
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${course.courseId}</td>
                    <td>${course.name}</td>
                    <td>${course.credit}</td>
                    <td>${course.totalHours}</td>
                    <td>${course.semester}</td>
                    <td>${course.teacher ? course.teacher.name : '未分配'}</td>
                    <td>${course.classroom ? course.classroom.building : '未分配'}</td>
                    <td>${course.major}</td>
                    <td>${course.courseType}</td>
                    <td>${course.year}</td>
                    <td class="actions">
                        <button class="edit-button" data-id="${safeId}">编辑</button>
                        <button class="delete-button" data-id="${safeId}">删除</button>
                    </td>
                `;
                
                // 添加点击事件监听器
                const editButton = row.querySelector('.edit-button');
                const deleteButton = row.querySelector('.delete-button');
                
                editButton.addEventListener('click', function() {
                    console.log("编辑按钮被点击，课程ID:", safeId);
                    openEditModal(safeId);
                });
                
                deleteButton.addEventListener('click', function() {
                    console.log("删除按钮被点击，课程ID:", safeId);
                    confirmDelete(safeId);
                });
                
                tableBody.appendChild(row);
            });
            console.log(`成功渲染 ${courses.length} 个课程`);
        }

        // 填充教师选项
        function populateTeacherOptions(teachers) {
            const addSelect = document.getElementById('addTeacherId');
            const editSelect = document.getElementById('editTeacherId');

            // 清空现有选项
            addSelect.innerHTML = '<option value="">--选择教师--</option>';
            editSelect.innerHTML = '<option value="">--选择教师--</option>';

            teachers.forEach(teacher => {
                const option = document.createElement('option');
                option.value = teacher.teacherId;
                option.textContent = `${teacher.name} (${teacher.teacherId})`;

                addSelect.appendChild(option.cloneNode(true));
                editSelect.appendChild(option);
            });
        }

        // 填充教室选项
        function populateClassroomOptions(classrooms) {
            const addSelect = document.getElementById('addClassroomId');
            const editSelect = document.getElementById('editClassroomId');

            // 清空现有选项
            addSelect.innerHTML = '<option value="">--选择教室--</option>';
            editSelect.innerHTML = '<option value="">--选择教室--</option>';

            classrooms.forEach(classroom => {
                const option = document.createElement('option');
                option.value = classroom.classroomId;
                option.textContent = `${classroom.classroomId} (${classroom.building}, 容量:${classroom.capacity})`;

                addSelect.appendChild(option.cloneNode(true));
                editSelect.appendChild(option);
            });
        }

        // 搜索课程
        function searchCourses() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            console.log("开始搜索课程，关键词:", searchTerm);
            if (searchTerm === '') {
                fetchCourses();
                return;
            }

            fetch(`/api/admin/courses/search?term=${encodeURIComponent(searchTerm)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("搜索课程响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        }
                        throw new Error('搜索课程失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("搜索课程结果:", data);
                    renderCourseList(data);
                })
                .catch(error => {
                    console.error('搜索课程出错:', error);
                });
        }

        // 打开添加课程模态框
        function openAddModal() {
            document.getElementById('addModal').style.display = 'block';
            // 清空表单
            document.getElementById('addCourseId').value = '';
            document.getElementById('addName').value = '';
            document.getElementById('addCredits').value = '';
            document.getElementById('addTotalHours').value = '';
            document.getElementById('addSemester').value = '大一上';
            document.getElementById('addTeacherId').value = '';
            document.getElementById('addClassroomId').value = '';
            document.getElementById('addMajor').value = '';
            document.getElementById('addCourseType').value = '必修课';
            document.getElementById('addYear').value = new Date().getFullYear();
            document.getElementById('addDescription').value = '';
        }

        // 关闭添加课程模态框
        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }

        // 添加课程
        function addCourse() {
            const courseData = {
                courseId: document.getElementById('addCourseId').value.trim(),
                name: document.getElementById('addName').value.trim(),
                credit: parseInt(document.getElementById('addCredits').value),
                totalHours: parseInt(document.getElementById('addTotalHours').value),
                semester: document.getElementById('addSemester').value,
                teacherId: document.getElementById('addTeacherId').value,
                classroomId: document.getElementById('addClassroomId').value,
                major: document.getElementById('addMajor').value.trim(),
                courseType: document.getElementById('addCourseType').value,
                year: parseInt(document.getElementById('addYear').value),
                description: document.getElementById('addDescription').value.trim()
            };

            console.log("准备添加新课程:", courseData);

            // 简单验证
            if (!courseData.courseId || !courseData.name || isNaN(courseData.credit) || isNaN(courseData.totalHours) || !courseData.major || isNaN(courseData.year)) {
                alert('请填写所有必填字段');
                return;
            }

            fetch('/api/admin/courses', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(courseData)
            })
                .then(response => {
                    console.log("添加课程响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 409) {
                            alert('课程ID已存在');
                            throw new Error('课程ID已存在');
                        }
                        return response.text().then(text => { throw new Error(text || '添加课程失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("添加课程成功:", data);
                    alert('添加课程成功');
                    closeAddModal();
                    fetchCourses();
                })
                .catch(error => {
                    console.error('添加课程出错:', error);
                });
        }

        // 打开编辑课程模态框
        function openEditModal(courseId) {
            console.log("准备打开编辑课程模态框，课程ID:", courseId);
            
            if (!courseId) {
                console.error("课程ID为空，无法打开编辑模态框");
                alert("错误：无法获取课程信息");
                return;
            }
            
            // 显示模态框并加载中状态
            document.getElementById('editModal').style.display = 'block';
            
            // 设置加载状态
            document.getElementById('editCourseForm').innerHTML = '<div style="text-align: center; padding: 20px;">加载中...</div>';
            
            fetch(`/api/admin/courses/${encodeURIComponent(courseId)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    console.log("获取课程详情响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                        } else if (response.status === 404) {
                            alert('课程不存在');
                        }
                        throw new Error('获取课程详情失败: ' + response.statusText);
                    }
                    return response.json();
                })
                .then(course => {
                    console.log("成功获取课程详情:", course);
                    
                    // 恢复表单内容
                    document.getElementById('editCourseForm').innerHTML = `
                        <div class="form-group">
                            <label for="editCourseId">课程ID</label>
                            <input type="text" id="editCourseId" name="courseId" readonly>
                        </div>
                        <div class="form-group">
                            <label for="editName">课程名称</label>
                            <input type="text" id="editName" name="name">
                        </div>
                        <div class="form-group">
                            <label for="editCredits">学分</label>
                            <input type="number" id="editCredits" name="credits" min="0" step="1">
                        </div>
                        <div class="form-group">
                            <label for="editTotalHours">总学时</label>
                            <input type="number" id="editTotalHours" name="totalHours" min="0" step="1">
                        </div>
                        <div class="form-group">
                            <label for="editSemester">开课学期</label>
                            <select id="editSemester" name="semester">
                                <option value="大一上">大一上</option>
                                <option value="大一下">大一下</option>
                                <option value="大二上">大二上</option>
                                <option value="大二下">大二下</option>
                                <option value="大三上">大三上</option>
                                <option value="大三下">大三下</option>
                                <option value="大四上">大四上</option>
                                <option value="大四下">大四下</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editTeacherId">授课教师</label>
                            <select id="editTeacherId" name="teacherId">
                                <!-- 教师选项将通过JavaScript动态加载 -->
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editClassroomId">教室</label>
                            <select id="editClassroomId" name="classroomId">
                                <!-- 教室选项将通过JavaScript动态加载 -->
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editMajor">专业</label>
                            <input type="text" id="editMajor" name="major">
                        </div>
                        <div class="form-group">
                            <label for="editCourseType">课程类型</label>
                            <select id="editCourseType" name="courseType">
                                <option value="公选课">公选课</option>
                                <option value="必修课">必修课</option>
                                <option value="选修课">选修课</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editYear">开课年份</label>
                            <input type="number" id="editYear" name="year" min="2000" max="2100">
                        </div>
                        <div class="form-group">
                            <label for="editDescription">课程描述</label>
                            <textarea id="editDescription" name="description"></textarea>
                        </div>
                        <div class="form-actions">
                            <button type="button" class="btn-cancel" onclick="closeEditModal()">取消</button>
                            <button type="button" class="btn-save" onclick="updateCourse()">保存</button>
                        </div>
                    `;
                    
                    // 重新获取教师和教室选项
                    fetchTeachers().then(() => {
                        fetchClassrooms().then(() => {
                            // 填充表单数据
                            document.getElementById('editCourseId').value = course.courseId;
                            document.getElementById('editName').value = course.name;
                            document.getElementById('editCredits').value = course.credit;
                            document.getElementById('editTotalHours').value = course.totalHours;
                            document.getElementById('editSemester').value = course.semester;
                            document.getElementById('editTeacherId').value = course.teacherId || '';
                            document.getElementById('editClassroomId').value = course.classroomId || '';
                            document.getElementById('editMajor').value = course.major;
                            document.getElementById('editCourseType').value = course.courseType;
                            document.getElementById('editYear').value = course.year;
                            document.getElementById('editDescription').value = course.description || '';
                        });
                    });
                })
                .catch(error => {
                    console.error('获取课程详情出错:', error);
                    document.getElementById('editCourseForm').innerHTML = `
                        <div style="text-align: center; color: red; padding: 20px;">
                            加载失败: ${error.message}
                            <div class="form-actions" style="margin-top: 20px;">
                                <button type="button" class="btn-cancel" onclick="closeEditModal()">关闭</button>
                            </div>
                        </div>
                    `;
                });
        }

        // 关闭编辑课程模态框
        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 更新课程
        function updateCourse() {
            const courseId = document.getElementById('editCourseId').value;
            const courseData = {
                courseId: courseId,
                name: document.getElementById('editName').value.trim(),
                credit: parseInt(document.getElementById('editCredits').value),
                totalHours: parseInt(document.getElementById('editTotalHours').value),
                semester: document.getElementById('editSemester').value,
                teacherId: document.getElementById('editTeacherId').value,
                classroomId: document.getElementById('editClassroomId').value,
                major: document.getElementById('editMajor').value.trim(),
                courseType: document.getElementById('editCourseType').value,
                year: parseInt(document.getElementById('editYear').value),
                description: document.getElementById('editDescription').value.trim()
            };

            console.log("准备更新课程:", courseData);

            // 简单验证
            if (!courseData.name || isNaN(courseData.credit) || isNaN(courseData.totalHours) || !courseData.major || isNaN(courseData.year)) {
                alert('请填写所有必填字段');
                return;
            }
            
            // 禁用保存按钮，防止重复提交
            const saveButton = document.querySelector('#editModal .btn-save');
            const cancelButton = document.querySelector('#editModal .btn-cancel');
            
            if (saveButton) {
                saveButton.disabled = true;
                saveButton.textContent = '保存中...';
            }
            if (cancelButton) {
                cancelButton.disabled = true;
            }

            fetch(`/api/admin/courses/${encodeURIComponent(courseId)}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(courseData)
            })
                .then(response => {
                    console.log("更新课程响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('课程不存在');
                            throw new Error('课程不存在');
                        }
                        return response.text().then(text => { throw new Error(text || '更新课程失败') });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("更新课程成功:", data);
                    alert('更新课程成功');
                    closeEditModal();
                    fetchCourses(); // 刷新课程列表
                })
                .catch(error => {
                    console.error('更新课程出错:', error);
                    alert('更新课程失败: ' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (saveButton) {
                        saveButton.disabled = false;
                        saveButton.textContent = '保存';
                    }
                    if (cancelButton) {
                        cancelButton.disabled = false;
                    }
                });
        }

        // 确认删除课程
        function confirmDelete(courseId) {
            console.log("确认是否删除课程，ID:", courseId);
            if (confirm('确定要删除这个课程吗？此操作不可撤销。')) {
                deleteCourse(courseId);
            }
        }

        // 删除课程
        function deleteCourse(courseId) {
            console.log("开始删除课程，ID:", courseId);
            fetch(`/api/admin/courses/${courseId}`, {
                method: 'DELETE',
                credentials: 'include'
            })
                .then(response => {
                    console.log("删除课程响应状态:", response.status);
                    if (!response.ok) {
                        if (response.status === 401) {
                            console.error("未授权，需要重新登录");
                            alert('未授权，请重新登录');
                            window.location.href = '/login';
                            throw new Error('未授权');
                        } else if (response.status === 404) {
                            alert('课程不存在');
                            throw new Error('课程不存在');
                        } else if (response.status === 409) {
                            alert('课程已有学生选课，无法删除');
                            throw new Error('课程已有学生选课');
                        }
                        return response.text().then(text => { throw new Error(text || '删除课程失败') });
                    }
                    return response.text();
                })
                .then(() => {
                    console.log("删除课程成功");
                    alert('删除课程成功');
                    fetchCourses();
                })
                .catch(error => {
                    console.error('删除课程出错:', error);
                });
        }
    </script>
</body>

</html>